<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\repair\controller;

use app\admin\service\NodeService;
use library\Controller;
use library\tools\Data;
use think\Db;
use \PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * 报修师傅模块后台
 * Class Menu
 * @package app\repair\controller
 */
class Sf extends Controller
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'bx_sf';

    /**
     * 报修用户数据管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '报修师傅管理';
        $this->_page($this->table, true);
    }
    /**
     * 导入用户
     * @auth true
     * @menu false
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function druser()
    {
        $this->title = '批量导入维修师傅';
        $this->fetch();
    }
    /**
     * 执行导入用户操作
     * @auth true
     * @menu false
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function dodruser()
    {
        //获取表格的大小，限制上传表格的大小5M
        $file_size = $_FILES['myfile']['size'];
        if ($file_size > 5 * 1024 * 1024) {
            $this->error('文件大小不能超过5M');
            exit();
        }

        //限制上传表格类型
        $fileExtendName = substr(strrchr($_FILES['myfile']["name"], '.'), 1);
        //application/vnd.ms-excel  为xls文件类型
        if ($fileExtendName != 'xls') {
            $this->error('必须为excel表格，且必须为xls格式！');
            exit();
        }

        if (is_uploaded_file($_FILES['myfile']['tmp_name'])) {
            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xls');

            $filename = $_FILES['myfile']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            // $highestColumn = $sheet->getHighestColumn();   // 取得总列数

            //定义$usersExits，循环表格的时候，找出已存在的用户。
            $usersExits = [];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'sf_name' => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue(),
                    'sf_sfzh' => $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                    'sf_tel' => $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue(),
                    'sf_gz' => $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue(),
                    'password' => md5($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue())


                ];
                //看下用户名是否存在。将存在的用户名保存在数组里。
                $userExist = db($this->table)->where('sf_sfzh', $data[$j - 2]['sf_sfzh'])->find();
                if ($userExist) {
                    array_push($usersExits, $data[$j - 2]['sf_sfzh']);
                }
            }
            //halt($usersExits);

            //如果有已存在的用户名，就不插入数据库了。
            if ($usersExits != []) {
                //把数组变成字符串，向前端输出。
                $c = implode(" <br/> ", $usersExits);
                $this->error('Excel中以下维修师傅身份证号已存在:<br/>' . $c."<br/>请检查后重新上传", "index", '', 20);
                exit();
            }

            //halt($data);
            //插入数据库
            $res = db($this->table)->insertAll($data);
            if ($res) {
                $this->success('上传成功！,总计上传'.$res.'人', 'index', '', 1);
            }
        }
    }
    /**
     * 添加系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 修改用户密码
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'pass');
        } else {
            $post = $this->request->post();
            if ($post['password'] !== $post['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            $result = NodeService::checkpwd($post['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save($this->table, ['id' => $post['id'], 'password' => md5($post['password'])], 'id')) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            // 刷新系统授权
            NodeService::applyUserAuth();
            // 用户权限处理
            $data['authorize'] = (isset($data['authorize']) && is_array($data['authorize'])) ? join(',', $data['authorize']) : '';
            // 用户账号重复检查
            if (isset($data['id'])) unset($data['username']);
            elseif (Db::name($this->table)->where(['sf_sfzh' => $data['sf_sfzh'],])->count() > 0) {
                $this->error("身份证号{$data['sf_sfzh']}已经存在，请使用其它账号！");
            }
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->authorizes = Db::name('SystemAuth')->where(['status' => '1'])->order('sort desc,id desc')->select();
        }
    }

    /**
     * 禁用系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除系统用户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }
}
